package com.example.administrator.szb.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.Yzm;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.eventbus.Event;
import com.example.administrator.szb.eventbus.EventBusUtil;
import com.example.administrator.szb.eventbus.eventbean.RegisterInfoBeanEvent;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.ChangeStatuUtil;
import com.example.administrator.szb.util.CheckMsgUtils;
import com.example.administrator.szb.util.Contants;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.KeyboardChangListenerUitl;
import com.example.administrator.szb.util.QTLog;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by 了不起的潘 on 2017/12/20.
 */

public class RegisterActivity_info extends BaseActivity {
    @Bind(R.id.register_image_back)
    LinearLayout registerImageBack;
    @Bind(R.id.register_edit_pass)
    EditText registerEditPass;
    @Bind(R.id.register_edit_yzm)
    EditText registerEditYzm;
    @Bind(R.id.register_text_yzm)
    TextView registerTextYzm;
    @Bind(R.id.register_new_edit_password)
    EditText registerNewEditPassword;
    @Bind(R.id.register_edit_password)
    EditText registerEditPassword;
    @Bind(R.id.register_button_register)
    Button registerButtonRegister;
    @Bind(R.id.register_sv_for_edit)
    ScrollView registerSvForEdit;

    String phone_num = "";//手机号
    String yzm_code = "";//验证码
    String password = "";//密码
    String password_sure = "";//确认密码
    int time = 60;//获取验证码倒计时
    String code_yzm;//请求下来的验证码
    private EditText editText;
    private int select = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_info_activity);
        //ChangeStatuUtil.setTranslucentStatus(this);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        initListener();
    }
    @Override
    protected void setBarColor() {
        ChangeStatuUtil.setTranslucentStatus(this);
    }
    private void initListener() {
        registerTextYzm.setEnabled(false);
        registerTextYzm.setTextColor(Color.parseColor("#ffbcbcbc"));
        registerEditPass.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (CheckMsgUtils.isMobileNO(registerEditPass.getText().toString().trim())){
                    registerTextYzm.setEnabled(true);
                    registerTextYzm.setTextColor(getResources().getColor(R.color.white));
                }else {
                    registerTextYzm.setEnabled(false);
                    registerTextYzm.setTextColor(Color.parseColor("#ffbcbcbc"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        registerEditYzm.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    editText = registerEditYzm;
                    select=-1;
                }
            }
        });
        registerNewEditPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    editText = registerNewEditPassword;
                    select=-1;
                }
            }
        });
        registerEditPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    editText = registerEditPassword;
                    select=-1;
                }
            }
        });
        registerEditPass.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    editText = registerEditPass;
                    select=-1;
                }
            }
        });


        //对键盘的监听
        KeyboardChangListenerUitl.KeyboardChangListener(this, new KeyboardChangListenerUitl.KeyboardCallback() {
            @Override
            public void doSomeThing() {
                registerSvForEdit.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (select==1){
                            return;
                        }
                        select=1;

                        registerSvForEdit.smoothScrollTo(0, registerSvForEdit.getHeight()/3);
                    }
                }, 0);
            }
        });
    }
    private void changes(){
        WindowManager wm = getWindowManager();

        int height = wm.getDefaultDisplay().getHeight();
        int[] position = new int[2];
        editText.getLocationOnScreen(position);
        QTLog.e(position[0] + "," + position[1]);
        registerSvForEdit.smoothScrollTo(0, height-position[1]);
    }

    @OnClick({R.id.register_image_back, R.id.register_text_yzm, R.id.register_button_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.register_image_back:
                finish();
                break;
            case R.id.register_text_yzm:
                requestYzm();
                break;
            case R.id.register_button_register:
                goToRegisterActivity();
                break;
        }
    }

    /**
     * 执行验证码操作
     */
    private void requestYzm() {
        phone_num = registerEditPass.getText().toString();

        if (TextUtils.isEmpty(phone_num)) {
            DialogUtil.showToast(this, "手机号不能为空");
        } else if (!CheckMsgUtils.isPhone(phone_num)) {
            DialogUtil.showToast(this, "请检查手机格式");
        } else {

            getYzm();
        }

        //loginSzb();
    }

    /**
     * 获取验证码方法
     */
    private void getYzm() {
        Map<String, String> map = new HashMap<String, String>();

        map.put("tel", phone_num);
        map.put("type", "1");//1代表注册验证码
        map.put("code", HttpUtil.getParam());
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, Yzm.class, URLAddress.URLBASE + URLAddress.URL_YZM, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                Yzm str = (Yzm) response;
                if (str.getResult() == 1) {
                    changeYzmStatu();
                    code_yzm = "";
                    code_yzm = str.getData().getCode() + "";
                    if (SampleApplicationLike.isDebugs)
                    DialogUtil.showToast(RegisterActivity_info.this,""+code_yzm);
                } else {
                    //Toasts.show(LoginNewActivity_two.this, ""+str.getErr_msg(), Toast.LENGTH_SHORT);
                    DialogUtil.showToast(RegisterActivity_info.this, "" + str.getErr_msg());
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                DialogUtil.showToast(RegisterActivity_info.this, "获取验证码失败，再试一次吧");
            }
        });
    }

    /**
     * 验证码按钮状态改变60秒重新发送
     */
    private void changeYzmStatu() {
        registerTextYzm.setEnabled(false);

        final Handler handlerTimeTask = new Handler();
        handlerTimeTask.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (time <= 0) {
                    registerTextYzm.setEnabled(true);
                    registerTextYzm.setText("获取验证码");
                    time = 60;
                } else {
                    registerTextYzm.setText(time + "秒后重新发送");
                    handlerTimeTask.postDelayed(this, 1000);
                }
                time--;
            }
        }, 1000);

    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void Toast_new(Event event){
//        Toasts.show(this, ""+event.toString(), Toast.LENGTH_SHORT);
//    }

    private void goToRegisterActivity() {
        boolean flag = checkInfo();
        //flag = true;
        if (flag) {
            startActivity(new Intent(this, RegisterActivity_new.class));
        }
    }

    private boolean checkInfo() {
        getInfo();
        String num1 = registerEditPassword.getText().toString().trim();
        String num2 = registerNewEditPassword.getText().toString().trim();
        if (TextUtils.isEmpty(phone_num)) {
            DialogUtil.showToast(this, "请输入手机号");
        } else if (!CheckMsgUtils.isPhone(phone_num)) {
            DialogUtil.showToast(this, "请检查手机格式");
        } else if (TextUtils.isEmpty(yzm_code)) {
            DialogUtil.showToast(this, "请输入验证码");
        } else if (yzm_code.length() < 4) {
            DialogUtil.showToast(this, "验证码为4位数字");
        } else if (!yzm_code.equals(code_yzm)) {
            DialogUtil.showToast(this, "验证码有误");
        } else if (!(num2.equals(num1))) {
            DialogUtil.showToast(this, "两次密码不一致");
        } else if (!Contants.passIsRight(num1)) {
            DialogUtil.showToast(this, "密码必须为字母或数字组合,长度最小为6");
        } else {
            return true;
        }
        return false;
    }

    private void getInfo() {
        phone_num = registerEditPass.getText().toString();
        yzm_code = registerEditYzm.getText().toString();
        password = registerNewEditPassword.getText().toString();
        password_sure = registerEditPassword.getText().toString();
    }

    /**
     * 为什么是onStop里面呢？因为这个方法是在下一个界面成功启动后调用的!!
     */

    @Override
    protected void onStop() {
        super.onStop();
        EventBusUtil.sendEvent(new Event(R.layout.register_info_activity, new RegisterInfoBeanEvent(phone_num, yzm_code, password, password_sure)));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 回车键登录
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //这里注意要作判断处理，ActionDown、ActionUp都会回调到这里，不作处理的话就会调用两次
        if (KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction()) {
            //处理事件
            goToRegisterActivity();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}
